import { mapGetters, mapMutations, mapActions } from 'vuex'
import _ from 'lodash'
const MESMIXIN = {
  data () {
    return {
      socketList: [],
      system: 0,
      tenantId: null,
      userId: null,
      count: 0
    }
  },
  computed: {
    ...mapGetters({
      'client': 'client',
      'userInfo': 'userInfo',
      'permissions': 'permissions',
      'msgCount': 'mes/msgCount',
      'msgSum': 'mes/msgSum'
    })
  },
  watch: {
    'userInfo.user_id': {
      handler (val) {
        if (!_.isNil(val)) {
          // 登录时初始化查询未读个数
          this.getReadNum(val)
        }
      },
      deep: true
    },
    $route (to, from) {
      if (to.path.includes('/main/factory/mine-message')) {
        this.count = 0
      }
    }
  },
  beforeDestroy () {
    // 取消订阅
    this.unsubscribeMsg()
  },
  mounted () {
    this.permissions.includes(115) && this.getSubscribe()
  },
  methods: {
    // 取消订阅
    unsubscribeMsg () {
      const subList = this.socketList
      if (!_.isEmpty(subList)) {
        subList.map(v => this.client.unsubscribe(v))
      }
      this.socketList = []
    },
    // 订阅
    getSubscribe () {
      if (_.isNil(this.client)) {
        setTimeout(() => {
          this.getSubscribe()
        }, 1500)
        return
      }
      this.onSubscribe(this.userInfo.user_id, (res) => {
        const member = JSON.parse(res.body)
        this.SET_NUM({ count: 1, type: 1 })
        this.SET_MSGBODY(member)
      })
    },
    onSubscribe (id, onMessageArrived) {
      this.tenantId = this.userInfo.tenant_id
      this.userId = this.userInfo.user_id
      // 订阅主题
      this.client.subscribe(
        `${this.CommonConfig.socketConfig.SOCKET_TOPIC.messageTopic.subscribeTopic}${this.tenantId}/${this.system}/${this.userId}`,
        onMessageArrived,
        { id: `${this.CommonConfig.socketConfig.SOCKET_TOPIC.messageTopic.subscribeTopic}${id}` }
      )
      this.socketList.push(`${this.CommonConfig.socketConfig.SOCKET_TOPIC.messageTopic.subscribeTopic}${id}`)
    },
    ...mapMutations({
      'SET_MSGBODY': 'mes/SET_MSGBODY',
      'SET_NUM': 'mes/SET_NUM'
    }),
    ...mapActions({
      'getReadNum': 'mes/getMsgRead' // 获取未读信息
    })
  }
}
export default MESMIXIN
